<script setup lang="tsx">
import { Message, Modal, type TreeInstance, type TreeNodeData } from '@arco-design/web-vue'
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import OrgAddModal from './OrgAddPanel.vue'
import RightMenu from './OrgRightMenu.vue'
import CellOrgNode from './CellOrgNode.vue'
import { OrgApi } from '@/apis'

defineOptions({
  name: 'OrgTree',
})

const emit = defineEmits<{
  (e: 'select', key: string, node: any): void
}>()

// 选中节点
const selectedKeys = ref()
const onSelect = (keys: Array<any>, data: any) => {
  selectedKeys.value = keys
  // tree select事件通过.node获取数据，手动调用直接获取拿data数据
  emit('select', keys[0], data.node || data)
}

const queryForm = reactive<OrgApi.OrgQuery>({
  sort: ['parentId,asc', 'sort,asc'],
})

interface TreeItem extends OrgApi.OrgResp {
  // popupVisible: boolean
}
const treeRef = ref<TreeInstance>()
const treeData = ref<TreeItem[]>([])
const loading = ref(false)
// 查询树列表
const getTreeData = async (query: OrgApi.OrgQuery = { ...queryForm }) => {
  try {
    loading.value = true
    treeData.value = await OrgApi.getTree(queryForm)
    await nextTick(() => {
      treeRef.value?.expandAll(true)
      if (treeData.value.length && treeData.value.length > 0) {
        onSelect([treeData.value[0].id], treeData.value[0])
      }
    })
  } finally {
    loading.value = false
  }
}

// 树查询
const keyword = ref('')
watch(keyword, (val) => {
  queryForm.name = val
  getTreeData()
})

const OrgAddModalRef = ref<InstanceType<typeof OrgAddModal>>()
// 右键菜单项点击
const onMenuItemClick = (mode: string, node: OrgApi.OrgResp) => {
  if (mode === 'add') {
    OrgAddModalRef.value?.onAdd()
  } else if (mode === 'update') {
    OrgAddModalRef.value?.onUpdate(node.id)
  } else if (mode === 'delete') {
    Modal.warning({
      title: '提示',
      content: `是否确定删除 [${node.name}]?`,
      hideCancel: false,
      okButtonProps: { status: 'danger' },
      onBeforeOk: async () => {
        try {
          await OrgApi.remove(node.id)
          Message.success('删除成功')
          getTreeData()
          return true
        } catch {
          return false
        }
      },
    })
  }
}

onMounted(() => {
  getTreeData()
})
</script>

<template>
  <div class="tree-wrapper">
    <a-input-search
      v-model="keyword"
      placeholder="输入关键词搜索"
      style="margin-bottom: 8px"
    />
    <a-tree
      ref="treeRef"
      class="tree"
      :data="(treeData as unknown as TreeNodeData[])"
      :field-names="{ key: 'id' }"
      block-node
      default-expand-all
      :selected-keys="selectedKeys"
      @select="onSelect"
    >
      <template #title="node">
        <CellOrgNode :name="node.name" :type="node.orgType" />
      </template>
      <template #extra="nodeData">
        <span class="tree-node-more">
          <a-trigger
            trigger="click"
            align-point
            animation-name="slide-dynamic-origin"
            auto-fit-transform-origin
            position="br"
            scroll-to-close
          >
            <IconMore class="tree-node-more-icon" />
            <template #content>
              <RightMenu
                v-permission="['system:org:manage']"
                :data="nodeData"
                @on-menu-item-click="onMenuItemClick"
              />
            </template>
          </a-trigger>
        </span>
      </template>
    </a-tree>
  </div>
  <OrgAddModal ref="OrgAddModalRef" @save-success="getTreeData" />
</template>

<style lang="less" scoped>
:deep(.arco-tree-node-title-text) {
  width: 100%;
  white-space: nowrap;
}

:deep(.arco-tree-node) {
  line-height: normal;
  border-radius: var(--border-radius-medium);
  &:hover {
    background-color: var(--color-secondary-hover);
  }

  .arco-tree-node-title {
    &:hover {
      background-color: transparent;
    }
  }
}

.tree-wrapper {
  overflow: hidden;
  height: 100%;

  .tree {
    overflow: auto;
    height: 100%;
  }
}

.tree-node-more {
  position: absolute;
  right: 8px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 22px;
  height: 22px;
  &:hover {
    // background-color: red;
    border: 1px solid var(--color-border-4);
    border-radius: 4px;
  }
}

.tree-node-more-icon {
  font-size: 12px;
  color: var(--color-text-2);
  height: 22px;
}
</style>
